/*
 * chrome://tabtreemix/content/links/setup.js
 *
 * original code by Bradley Chapman
 * modified and developped by Hemiola SUN
 * modified again by Bradley Chapman
 *
 */
var gObserver =      Components.classes["@mozilla.org/observer-service;1"]
                     .getService(Components.interfaces.nsIObserverService);

var __contentAreaClick;
var __BrowserOpenTab;
var __BrowserLoadURL;
var __SearchLoadURL;
var __EMopenURL;
var __openUILink;

/**
 * @brief Install the link-handling functions of Tab Tree Mix.
 *
 * @returns		Nothing.
 */
function TMP_TBP_init()
{
   __contentAreaClick = window.contentAreaClick;
   __BrowserOpenTab = window.BrowserOpenTab;
   __BrowserLoadURL = window.BrowserLoadURL;
   if ("SearchLoadURL" in window) {
      __SearchLoadURL = window.SearchLoadURL;
      window.SearchLoadURL = TMP_SearchLoadURL;
   }
   __openUILink = window.openUILink;

  var eStrings = document.getElementById("extensionsStrings");
  if (eStrings) {
      // we're in the EM
      __EMopenURL = openURL;
      openURL = TMP_openURL;

      // catch call to tabmix options from EM
      eval("gExtensionsViewController.commands.cmd_options ="+gExtensionsViewController.commands.cmd_options.toString().replace(
      'var optionsURL = aSelectedItem.getAttribute("optionsURL");',
      '$& \ if (TMP_cmd_options(optionsURL)) return;'
      ));
  }

  // with MR Tech's local install
  if (typeof(Local_Install) == "object") {
    // use TMP call to TMP Options
    var _aURL = "'chrome://tabtreemix/content/pref/pref-tabmix.xul'";
    eval("Local_Install.createDropDownMenu ="+Local_Install.createDropDownMenu.toString().replace(
    'aMenuItem.setAttribute("oncommand", thisAction + "; event.stopPropagation();");',
    'if (thisAction.indexOf(_aURL) != -1) thisAction = "TMP_cmd_options(" + _aURL + ")"; \ $&'
    ));
  }
  
  window.contentAreaClick = TMP_contentAreaClick_caller;
  window.BrowserOpenTab = TMP_BrowserOpenTab;
  window.BrowserLoadURL = TMP_BrowserLoadURL;
  window.openUILink = TMP_openUILink;
}

/**
 * @brief Remove the link-handling functions of Tab Tree Mix.
 *
 * @returns		Nothing.
 */
function TMP_TBP_exit()
{
    var eStrings = document.getElementById("extensionsStrings");
    if (eStrings) {
      // we're in the EM
      openURL = __EMopenURL;
    }

    window.BrowserOpenTab = __BrowserOpenTab;
    window.contentAreaClick = __contentAreaClick;
    window.BrowserLoadURL = __BrowserLoadURL;
    if ("SearchLoadURL" in window)
      window.SearchLoadURL = __SearchLoadURL;
    window.openUILink = __openUILink;

    return;
}

/**
 * @brief Force-call the window observer at least one time.
 *
 * @returns		Nothing.
 */
function TMP_TBP_Startup()
{
    // force-call the observer once, in order to kill new windows faster
    TMP_DOMWindowOpenObserver.onObserve(window, TMP_DOMWindowOpenObserver);

    // make tabmix compatible with ezsidebar
    var TMP_BrowserStartup = "BrowserStartup" in window ? "BrowserStartup" : "Startup";
    if ('__ezsidebar__'+TMP_BrowserStartup in window)
      TMP_BrowserStartup =  '__ezsidebar__'+TMP_BrowserStartup;

    if (!gPrefService)
         gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
                  .getService(Components.interfaces.nsIPrefBranch);

    var stringBundle = document.getElementById("tmp-string-bundle");
    var tabmix_loading = stringBundle.getString("session.loading.label") + "...";

    var windowOpeneByTabmix = window.name.indexOf("tabmix") != -1;
    var firstWindow = numberOfWindows() == 1;

    var sessionStore;
    if (typeof(BrowserOpenAddonsMgr) == "function") {
      window.setSession = true; // don't trigger alert message befor window is load
      sessionStore = TMP_getBoolPref("", "browser.sessionstore.enabled", true);
      window.setSession = false;
    }

    var sessionManager = gPref.getBoolPref("extensions.tabmix.sessions.manager");
    var crashRecovery = gPref.getBoolPref("extensions.tabmix.sessions.crashRecovery");
    var afterRestart = false;
    try {
       afterRestart = gPref.getBoolPref("extensions.tabmix.resume_session_once");
    } catch (ex) {}

    var restoreOrAsk = gPref.getIntPref("extensions.tabmix.sessions.onStart") < 2 || afterRestart;
    var afterCrash = gPref.prefHasUserValue("extensions.tabmix.sessions.crashed");
    if (afterCrash)
       gPref.clearUserPref("extensions.tabmix.sessions.crashed");

    // don't load home page on first window if session manager or crash recovery is enabled
    window.isLoadHomePage = true;
    if (!sessionStore && ((sessionManager && windowOpeneByTabmix) ||
         (firstWindow && crashRecovery && afterCrash) ||
         (firstWindow && sessionManager && restoreOrAsk))) {
            delete window.isLoadHomePage;
            eval("window."+TMP_BrowserStartup+" ="+window[TMP_BrowserStartup].toString().replace(
              'uriToLoad = window.arguments[0];',
              'uriToLoad = gHomeButton.getHomePage() == window.arguments[0] ? "about:blank" : window.arguments[0];'
            ).replace(
              'var sidebarSplitter;',
              'if (uriToLoad && !gIsLoadingBlank) for (var i = 0; i < gBrowser.mTabContainer.childNodes.length ; i++) gBrowser.mTabContainer.childNodes[i].loadOnStartup = true;\
               if (uriToLoad == "about:blank" || window.name.indexOf("tabmix") != -1) {\
               var aBrowser = gBrowser.mCurrentBrowser;\
               aBrowser.contentDocument.title = tabmix_loading;\
               aBrowser.mIconURL = "chrome://tabtreemix/skin/tmp.png";\
               gBrowser.mCurrentTab.setAttribute("image", aBrowser.mIconURL);}\
               var sidebarSplitter;'
            ));
    }

    var rExp = /BMSVC.readBookmarks\(\);|window.controllers.appendController\(PlacesController\);/
    eval("delayedStartup ="+delayedStartup.toString().replace(rExp,'$& \ TMP_delayedStartup();'));

    // look for installed extensions that are incompatible with tabmix
    if (gPref.getBoolPref("extensions.tabmix.disableIncompatible"))
      if(gIsOldBrowser) // in 1.0.x we can get error at startup
         window.setTimeout(disableExtensions, 0);
      else
         disableExtensions();

    // set the corect getTitleFromBookmark function
    window._getBookmarkTitle = gIsPlaces ? TMP_Places._getBookmarkTitle :
                                           TMP_Bookmark._getBookmarkTitle;

    // make tabmix compatible with menumanipulator and MenuEdit extensions
    // add bookmark options and tabmix function to context menu for tabs befor BrowserStartup
    window.gNavigatorBundle = window.document.getElementById("bundle_browser");
    if(window.addBookmarkMenuitems) {
      window.addBookmarkMenuitems();
      window.addBookmarkMenuitems = function(){}
    }
    if(window.AugmentTabs) {
      window.AugmentTabs.init = function(){}
    }
    window.TM_creatMenuItems();

    // if nglayout.debug.disable_xul_cache == true sometimes sessionHistory act strange
    // especially with many extensions installed
    var pref = "nglayout.debug.disable_xul_cache";
    var openFromPlaces;
    if ("openFromPlaces" in window) {
      openFromPlaces = window.openFromPlaces;
      delete window.openFromPlaces;
    }

    if ((!firstWindow && !windowOpeneByTabmix || openFromPlaces) && gPref.prefHasUserValue(pref) && gPref.getBoolPref(pref))
      window.setTimeout(window[TMP_BrowserStartup], 0);
    else
      window[TMP_BrowserStartup]();

    return;
}

function getTitleFromBookmark(url)
{
   var title = _getBookmarkTitle(url);
   if (title || !window.gIeTab)
      return title;

   // if IE Tab is installed try to find url with or without the prefix
   var ietab = "chrome://ietab/content/reloaded.html?url="
   if (url.indexOf(ietab) == 0)
      title = _getBookmarkTitle(url.replace(ietab, ""));
   else
      title = _getBookmarkTitle(ietab + url);

   return title;
}

function TMP_delayedStartup()
{
  if (gIsFirefox2 && numberOfWindows() == 1) {
    // make sure that we don't enable both sessionStore and session manager
    TMP_SessionStore.setService(1, true);
    if (gPref.getBoolPref("browser.sessionstore.enabled")) {
      // Add attribute to nsSessionStore persistTabAttribute after delay
      // we call this after nsSessionStore.init
      window.setTimeout(TMP_SessionStore.init, 2000, false);
    }
  }

  // set title at startup if we not use session manager
  // startup page or home page load befor BMSVC
  if (gPrefService.getBoolPref("extensions.tabmix.titlefrombookmark")) {
    for (var i = 0; i < gBrowser.mPanelContainer.childNodes.length ; i++) {
      var aBrowser = gBrowser.getBrowserAtIndex(i);
      var aUrl = aBrowser.contentDocument.baseURI;
      aUrl = (aUrl) ? aUrl : aBrowser.currentURI.spec ;
      var bookMarkName = getTitleFromBookmark(aUrl);
      if (bookMarkName && aBrowser.contentDocument.title != bookMarkName)
        aBrowser.contentDocument.title = bookMarkName;
    }
  }
}

// this must run befor all
function TMP_beforStartup()
{
    var wintype = window.document.documentElement.getAttribute("windowtype");
    if (wintype != "navigator:browser")
      return;

    var _Browser = document.getElementById("content");
    // remove call to "arrowscrollbox" by "this.mTabContainer.mTabstrip" we don't use it in tabmix
    if (typeof(BrowserOpenAddonsMgr) == "function") { // we are in FF 2.0 +
        eval("_Browser.moveTabTo ="+_Browser.moveTabTo.toString().replace(
             'this.mTabContainer.insertBefore(aTab, this.mTabContainer.childNodes[aIndex]);',
             'if (this.mTabContainer.childNodes.length <= aIndex) this.mTabContainer.appendChild(aTab); \
              else $& '
            ).replace(
             'this.mTabContainer.mTabstrip.scrollBoxObject.ensureElementIsVisible(this.mCurrentTab);',
             ''
        ));

        eval("_Browser.addTab ="+_Browser.addTab.toString().replace(
             'setTimeout(_delayedUpdate, 0, this.mTabContainer);',
             ''
            ).replace(
             'this.mTabContainer.mTabstrip.scrollBoxObject.scrollBy(this.mTabContainer.firstChild.boxObject.width, 0);',
             ''
        ));

        eval("_Browser.removeTab ="+_Browser.removeTab.toString().replace(
             'setTimeout(_delayedUpdate, 0, this.mTabContainer);',
             ''
        ));
    }

   // Wire up Tabmix functions to mTabProgressListener
   eval("_Browser.addTab ="+_Browser.addTab.toString().replace(
      'var tabListener = this.mTabProgressListener(t, b, blank);',
      '$& \ tabListener = TMP_ProgressListener.init(tabListener);'
   ));

   eval("_Browser.enterTabbedMode ="+_Browser.enterTabbedMode.toString().replace(
      'filter.addProgressListener(listener, Components.interfaces.nsIWebProgress.NOTIFY_ALL);',
      'listener = TMP_ProgressListener.init(listener); \ $&'
   ));

}
TMP_beforStartup();
